package com.conferenceroom.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.conferenceroom.dto.AjaxResult;
import com.conferenceroom.entity.User;
import com.conferenceroom.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping
    public AjaxResult getAllUsers() {
        List<User> users = userService.list();
        return users == null || users.isEmpty() ? AjaxResult.fail("未查询到用户") : AjaxResult.success(users);
    }

    @GetMapping("/page")
    public AjaxResult getAllUsersByPage(@RequestParam(defaultValue = "1") Integer pageNum,
                                        @RequestParam(defaultValue = "10") Integer pageSize) {
        Page<User> page = new Page<>(pageNum, pageSize);
        Page<User> userPage = userService.page(page);
        return AjaxResult.success(userPage);
    }


    @GetMapping("/{id}")
    public AjaxResult getUserById(@PathVariable Integer id) {
        User user = userService.getById(id);
        return user != null ? AjaxResult.success(user) : AjaxResult.fail("用户不存在");
    }

    @PostMapping
    public AjaxResult saveUser(@RequestBody User user) {
        boolean saved = userService.save(user);
        return saved ? AjaxResult.success("新增成功") : AjaxResult.fail("新增失败");
    }

    @PutMapping("/{id}")
    public AjaxResult updateUser(@PathVariable Integer id, @RequestBody User user) {
        user.setUserId(id);
        boolean updated = userService.updateById(user);
        return updated ? AjaxResult.success("更新成功") : AjaxResult.fail("更新失败");
    }

    @DeleteMapping("/{id}")
    public AjaxResult deleteUserById(@PathVariable Integer id) {
        boolean deleted = userService.removeById(id);
        return deleted ? AjaxResult.success("删除成功") : AjaxResult.fail("删除失败");
    }

    @PostMapping("/page/condition")
    public AjaxResult pageByCondition(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestBody User user) {

        Page<User> page = new Page<>(pageNum, pageSize);
        IPage<User> result = userService.pageByCondition(page, user);

        return AjaxResult.success(result);
    }


    @GetMapping("/search/userid")
    public AjaxResult searchUserIdsByUsername(@RequestParam String username) {
        List<Map<String, Object>> result = userService.getUserIdsByUsername(username);
        if (result == null || result.isEmpty()) {
            return AjaxResult.fail("未找到匹配的用户");
        }
        return AjaxResult.success(result);
    }


}
